<template>
  <van-form
    ref="formRef"
    class="flex flex-col items-center"
    @submit="handleSubmit"
  >
    <van-field
      v-model="formData.username"
      class="enter-y mb-4 items-center !rounded-md"
      name="username"
      placeholder="用户名"
    >
      <template #left-icon>
        <i class="i-ph:user-bold mr-2 text-lg" />
      </template>
    </van-field>
    <van-field
      v-model="formData.password"
      class="enter-y mb-4 items-center !rounded-md"
      :type="switchPassType ? 'password' : 'text'"
      name="password"
      placeholder="密码"
      @click-right-icon="switchPassType = !switchPassType"
    >
      <template #left-icon>
        <i class="i-iconamoon:lock-bold mr-2 text-lg" />
      </template>
      <template #right-icon>
        <i v-if="switchPassType" class="i-mdi:eye-outline mr-2 text-lg" />
        <i v-else class="i-mdi:eye-off mr-2 text-lg" />
      </template>
    </van-field>

    <van-button
      class="enter-y !mb-4 !rounded-md"
      type="primary"
      block
      native-type="submit"
      :loading="loading"
    >
      登 录
    </van-button>
  </van-form>
</template>

<script setup lang="ts">
import { showLoadingToast } from 'vant'
import type { FormInstance } from 'vant'
import { getLoginIn } from '@/api/login'

const route = useRoute()

const formRef = ref<FormInstance>()
const loading = ref(false)
const switchPassType = ref(true)
const formData = reactive({
  username: 'xdanger1234',
  password: 'Lj$535016256',
})

function handleSubmit() {
  formRef.value
    ?.validate()
    .then(async () => {
      try {
        loading.value = true
        showLoadingToast('登录中...')
        const res: any = await getLoginIn({
          username: formData.username,
          password: formData.password,
          code: '',
          source: 'WEB',
          code_value: 'RuicoiySH5QAIih9',
        })

        // 将用户登录成功返回的token存储在cookie当中，用户登录成功的标识
        const token = useCookie('token')
        token.value = res?.data?.token
        loading.value = false

        // 跳转
        // @ts-ignore
        navigateTo(route?.query?.from || '/', { replace: true })
      } finally {
        loading.value = false
      }
    })
    .catch(() => {
      console.error('验证失败')
    })
}

onMounted(() => {})

// ui布局
definePageMeta({
  layout: 'login',
})
</script>

<style scoped lang="scss"></style>
